#include <iostream>
#include <cerrno>  // <==> errno.h
#include <cstring> // <==> string.h
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>

const int size = 1024;

std::string GetOtherMessage()
{
    static int cnt = 0;// 静态变量，全局的，在函数能使用
    std::string messageid = std::to_string(cnt); // stoi string -> int
    cnt++;
    pid_t id = getpid();
    std::string stringid = std::to_string(id);

    std::string message = "messageid: ";
    message += messageid;
    message += "stringid: ";
    message += stringid;

    return message;
}

// 子进程进行写入
void SubProcessWrite(int wfd)
{
    int pipesize = 0;
    std::string message = "father,I am your son process!";
    char c = 'A';
    while(true)
    {
        std::cerr << "+++++++++++++++++++++++++++++++++" << std::endl;
        std::string info = message + GetOtherMessage(); // 这条消息，就是我们子进程发给父进程的消息
        write(wfd,info.c_str(),info.size()); // 写入管道的时候，没有写入\0, 有没有必要？没有必要
        //sleep(1);

        std::cerr << info << std::endl;

        //sleep(1); // 子进程写慢一点
        // write(wfd, &c, 1);
        // // std::cout << "pipesize: " << ++pipesize << std::endl;
        // std::cout << "pipesize: " << ++pipesize << " write charator is : "<< c++ << std::endl;
        // sleep(1);
        // if(c == 'G') break;
        // break;
    }
    std::cout << "child quit... " << std::endl; 
}


// 父进程进行读取
void FatherProcessRead(int rfd)
{
    char buffer[size];
    while(true)
    {
        //sleep(500);
        sleep(2);
        std::cout << "-----------------------------------" << std::endl;
        ssize_t n = read(rfd,buffer,sizeof(buffer) - 1); // strlen()
        // 返回值大于0表示成功读取
        if(n > 0)
        {
            buffer[n - 1] = 0;// \0
            std::cout << buffer << std::endl;
        }
        // 返回值是0，表示写端直接关闭了，我们读到了文件的结尾
        else if(n == 0)
        {
            std::cout << "client quit, father get return val: " << n << " father quit too!" << std::endl;
            break;
        }
        // 返回值小于0表示读取错误
        else if(n < 0)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
        // std::cout << "father get return val: " << n <<std::endl;
        // sleep(1);
        // break;
    }
}

// 父进程进行读取
void FatherProcessRead(int rfd)
{
    char buffer[size];
    while(true)
    {
        sleep(2);
        std::cout << "-----------------------------------" << std::endl;
        ssize_t n = read(rfd,buffer,sizeof(buffer) - 1); // strlen()
        if(n > 0)
        {
            buffer[n - 1] = 0;// \0
            std::cout << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "client quit, father get return val: " << n << " father quit too!" << std::endl;
            break;
        }
        else if(n < 0)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
}

int main()
{
    // close(0); // 关闭文件描述符
    // 1、创建管道
    int pipefd[2];
    int n = pipe(pipefd); // 输出型参数 rfd wfd
    // 返回0表示成功，不等于0则失败且更新错误码
    if(n != 0)
    {
        std::cerr << "errno: "<< errno << "errstring: " << strerror(errno) << std::endl;
        return 1;
    }
    // pipefd[0] 读(0 -> 嘴巴 -> r) pipefd[1] 写(1 -> 笔 -> w)
    std::cout << "pipefd[0]: " << pipefd[0] << ",pipefd[1]: " << pipefd[1] << std::endl;
    // 2、创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        std::cout << "子进程关闭不需要的fd了，准备发消息了" << std::endl;
        // 子进程  --write
        // 3、关闭不需要的文件描述符 read
        close(pipefd[0]);

        SubProcessWrite(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    sleep(1);
    // 父进程
    // 3、关闭不需要的文件描述符 write
    std::cout << "父进程关闭不需要的fd了，准备收消息了" << std::endl;
    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);
    std::cout << "5s,father close rfd" << std::endl;
    sleep(5);
    close(pipefd[0]);

    // 回收子进程
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    // 返回值大于0回收成功
    if(rid > 0)
    {
        std::cout << "wait child process done, exit sig: " << (status & 0x7f) << std::endl;
        std::cout << "wait child process done, exit code(ign): " << ((status >> 8) & 0xFF) << std::endl;
    }
    return 0;
}

// // 测试创建管道
// int main()
// {
//     close(0);
//     // 1、创建管道
//     int pipefd[2];
//     int n = pipe(pipefd); // 输出型参数 rfd wfd
//     // 返回0表示成功，不等于0则失败且更新错误码
//     if(n != 0)
//     {
//         std::cerr << "errno: "<< errno << "errstring: " << strerror(errno) << std::endl;
//         return 1;
//     }
//     // pipefd[0] 读(0 -> 嘴巴 -> r) pipefd[1] 写(1 -> 笔 -> w)
//     // 打印文件描述符
//     std::cout << "pipefd[0]: " << pipefd[0] << ",pipefd[1]: " << pipefd[1] << std::endl;

//     return 0;
// }